<template>
  <div class="resource-container">
    <div class="resource-aside">
      <CollapseSelect @selected-change="onAsideSelectedChange" :list="resourceViewTypeList" />
    </div>
    <div class="resource-content">
      <el-container>
        <el-header>
          <div class="resource-header">
            <template v-if="!checkList.length">
              <el-button type="primary" @click="visibleUpload = true">
                <el-icon class="el-icon--left"><Upload /></el-icon>上传
              </el-button>
              <el-button plain type="primary" @click="createFolder()"
                ><el-icon class="el-icon--left"><Plus /></el-icon>新建文件夹</el-button
              >
            </template>
            <template v-else>
              <el-button plain type="danger" @click="deleteResource()"
                ><el-icon class="el-icon--left"><Delete /></el-icon>删除</el-button
              >
            </template>
          </div>
          <div class="mt10px mb-10px flex items-center">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              :disabled="!list.length"
            >
              全选
            </el-checkbox>
            <el-divider direction="vertical" />
            <!-- 导航页 -->
            <el-breadcrumb separator=">">
              <el-breadcrumb-item
                v-for="(item, index) in breadcrumbList"
                :key="index"
                @click="handleBreadcrumbClick(item, index)"
                >{{ item.name }}</el-breadcrumb-item
              >
            </el-breadcrumb>
          </div>
        </el-header>
        <el-main v-loading="loading">
          <div class="file-content">
            <el-checkbox-group
              class="file-content"
              v-model="checkList"
              @change="handleCheckedGroupChange"
            >
              <resourceItem
                v-for="item in list"
                :item="item"
                :isSelected="checkList.includes(item.id)"
                :key="item.id"
                @click="handleFileClick(item)"
                @create-folder="createFolder"
                @delete-resource="deleteResource"
                @permission-management="permissionManagement"
              />
            </el-checkbox-group>
            <ElEmpty v-if="!list.length" description="当前文件夹为空" />
          </div>
          <ReachBottom class="mx-auto" :loading="loading" @on-reach-bottom="handleReachBottom" />
        </el-main>
      </el-container>
    </div>
    <uploadFileDialog v-model="visibleUpload" :query="oploadQueryParams" @success="getList(true)" />
    <FileViewDialog v-model="resourceDialogVisible" :src="currentResourceUrl" append-to-body />
    <createFolderOrRenameDialog
      ref="createFolderOrRenameDialogRef"
      :query="oploadQueryParams"
      @success="getList(true)"
    />
  </div>
</template>

<script setup lang="ts">
import { Delete, Plus, Upload } from '@element-plus/icons-vue'
import { ResourceFileApi, ResourceFileVO } from '@/api/school/resource'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import resourceItem from './components/resourceItem.vue'
import uploadFileDialog from './components/uploadFileDialog.vue'
import createFolderOrRenameDialog from './components/createFolderOrRenameDialog.vue'
import { usePageList } from '@/hooks/web/usePageList'
import { useRoute } from 'vue-router'
const route = useRoute()
const message = useMessage()
/** 成果库 列表 */
defineOptions({ name: 'SchoolResourceFile' })
const queryParams = reactive({
  parentId: 0,
  resourceCode: '',
  resourceType: undefined,
  rightStatus: 0,
  name: undefined,
  type: undefined,
  status: undefined,
  createTime: []
})
const oploadQueryParams = computed(() => {
  return {
    rightStatus: parseInt(queryParams.rightStatus.toString().slice(0, 1)),
    parentId: queryParams.parentId,
    resourceCode: queryParams.resourceCode,
    directory: `resource/${queryParams.resourceCode}`
  }
})
// 资源查看权限分类
const resourceViewTypeList: any = computed(() => getIntDictOptions(DICT_TYPE.SCHOOL_RIGHT_STATUS))

const visibleUpload = ref(false) // 上传弹窗的显示
const resourceDialogVisible = ref(false)
const currentResourceUrl = ref('')

const breadcrumbList: any = ref([
  {
    name: '全部文件',
    path: '/school/resource',
    id: 0,
    parentId: 0
  }
])
const checkList: any = ref([])
const checkAll = ref(false)
const isIndeterminate = ref(false)
const createFolderOrRenameDialogRef = ref()
const {
  list,
  loading,
  getList,
  queryParams: pageQueryParams,
  handleReachBottom
}: any = usePageList({
  toast: message,
  queryFn: ResourceFileApi.getResourceFilePage,
  query: queryParams,
  complete() {
    resetCheck()
  }
})
pageQueryParams.pageSize = 48
const handleCheckAllChange = (val: boolean) => {
  checkList.value = val
    ? list.value
        .filter((item) => !(item.rightStatus === 1 && item.operRight === 1))
        .map((item) => item.id)
    : []
  isIndeterminate.value = false
}
const handleCheckedGroupChange = (value: any) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === list.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < list.value.length
}
// 重置资源选中状态
const resetCheck = () => {
  checkList.value = []
  checkAll.value = false
  isIndeterminate.value = false
}
const handleBreadcrumbClick = (item: any, index: number) => {
  queryParams.parentId = item.id
  breadcrumbList.value.splice(index + 1, breadcrumbList.value.length - index - 1)
  getList(true)
}
// 删除资源
const deleteResource = async (item?: any) => {
  if (!item && checkList.value.length === 0) {
    ElMessage.warning('请选择要删除的资源')
    return
  }
  try {
    const action = await ElMessageBox.confirm('确定删除选中的资源吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    if (action === 'confirm') {
      const deleteApi = item
        ? ResourceFileApi.deleteResourceFile
        : ResourceFileApi.deleteResourceFileList
      const deleteData = item
        ? item.id
        : {
            ids: checkList.value.join(',')
          }
      const data = await deleteApi(deleteData)
      if (data) {
        ElMessage.success('删除成功')
        getList(true)
      }
    }
  } catch (error) {
    console.log(error)
  }
}
const createFolder = async (item?: any) => {
  createFolderOrRenameDialogRef.value.open(item)
}
const permissionManagement = async (item: any) => {
  createFolderOrRenameDialogRef.value.open(item, 'permission')
}
const handleFileClick = (item: ResourceFileVO) => {
  if (item.resourceType === 'file') {
    currentResourceUrl.value = item.url
    resourceDialogVisible.value = true
  } else {
    queryParams.parentId = item.id
    breadcrumbList.value.push({
      name: item.name,
      id: item.id,
      parentId: item.parentId
    })
    getList(true)
  }
}

const onAsideSelectedChange = (val: any) => {
  queryParams.rightStatus = val
  queryParams.parentId = 0
  breadcrumbList.value.splice(1, breadcrumbList.value.length - 1)
  getList(true)
}
// 路由到 resourceCode 映射关系
const pathToAssetTypeMap = {
  '/resource/achievement': 'achievement', //成果库
  '/resource/archives': 'archives', //档案库
  '/resource/contracts': 'contracts' //合同库
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(
  () => route.path,
  (path) => {
    // 匹配路径并赋值 resourceCode
    queryParams.resourceCode = pathToAssetTypeMap[path] || 'archives'
    getList(true)
  },
  {
    immediate: true //立即执行一次
  }
)
</script>

<style lang="scss" scoped>
.resource-container {
  display: flex;
  min-height: $content-height;

  .tab-pane-content {
    background-color: #fff;
  }

  .resource-aside {
    width: 200px;
    min-height: $content-height;
    background-color: #fff;
    border-right: solid 1px var(--el-menu-border-color);
  }

  .resource-content {
    height: $content-height;
    background-color: #fff;
    flex: 1;
  }

  .file-content {
    display: flex;
    flex-wrap: wrap;
    gap: 20px 30px;
    font-size: unset;
    line-height: unset;
  }

  .resource-header {
    display: flex;
    height: 48px;
    border-bottom: 1px solid #e9e9e9;
    align-items: center;
  }

  :deep() {
    .el-tabs__header {
      margin-right: 0;
      background-color: #fff;
    }

    .el-menu {
      height: 100%;
    }

    .el-container {
      height: 100%;
    }

    .el-header {
      height: auto;
    }

    .el-breadcrumb {
      .el-breadcrumb__item {
        &:not(:last-child) {
          .el-breadcrumb__inner {
            color: color-mix(in oklch, var(--el-color-primary), transparent 15%);
            cursor: pointer !important;
            transition: color 0.3s;

            &:hover {
              color: var(--el-color-primary);
            }
          }
        }
      }
    }

    .el-empty {
      margin: 0 auto;
    }
  }
}
</style>
